// ==UserScript==
// @name         Cookie工具增强版
// @namespace    https://gitee.com/cao15110
// @version      1.0
// @author       ws
// @description  增强版Cookie工具，包含设置、一键复制和展示细节功能
// @license      GPL-3.0-only
// @match        *://*/*
// @require      https://fastly.jsdelivr.net/gh/WhiteSevs/TamperMonkeyScript@86be74b83fca4fa47521cded28377b35e1d7d2ac/lib/CoverUMD/index.js 
// @require      https://fastly.jsdelivr.net/npm/@whitesev/utils@2.9.0/dist/index.umd.js 
// @require      https://fastly.jsdelivr.net/npm/@whitesev/domutils@1.7.0/dist/index.umd.js 
// @require      https://fastly.jsdelivr.net/npm/qmsg@1.5.0/dist/index.umd.js 
// @require      https://fastly.jsdelivr.net/gh/WhiteSevs/TamperMonkeyScript@886625af68455365e426018ecb55419dd4ea6f30/lib/CryptoJS/index.js 
// @connect      *
// @grant        GM.cookie
// @grant        GM_cookie
// @grant        GM_deleteValue
// @grant        GM_getResourceText
// @grant        GM_getValue
// @grant        GM_info
// @grant        GM_registerMenuCommand
// @grant        GM_setValue
// @grant        GM_unregisterMenuCommand
// @grant        GM_xmlhttpRequest
// @grant        unsafeWindow
// @run-at       document-start
// ==/UserScript==

(function (Qmsg, DOMUtils, Utils, CryptoJS) {
  'use strict';

  // 保留原始代码中的核心功能模块
  const _GM = typeof GM !== "undefined" ? GM : void 0;
  const _GM_cookie = typeof GM_cookie !== "undefined" ? GM_cookie : void 0;
  const _GM_getValue = typeof GM_getValue !== "undefined" ? GM_getValue : void 0;
  const _GM_setValue = typeof GM_setValue !== "undefined" ? GM_setValue : void 0;
  const _unsafeWindow = typeof unsafeWindow !== "undefined" ? unsafeWindow : window;

  // 存储工具类 - 用于保存用户设置
  class StorageUtils {
    constructor(storageKey) {
      this.storageKey = storageKey;
    }

    getValue(key, defaultValue) {
      const data = _GM_getValue(this.storageKey) || {};
      return data[key] ?? defaultValue;
    }

    setValue(key, value) {
      const data = _GM_getValue(this.storageKey) || {};
      data[key] = value;
      _GM_setValue(this.storageKey, data);
    }
  }

  // 初始化存储工具
  const cookieStorage = new StorageUtils('cookie_tool_settings');

  // Cookie工具类
  class CookieTool {
    constructor() {
      this.cookieMethods = [
        { id: 'gm', name: 'GM API获取' },
        { id: 'document', name: 'document.cookie获取' },
        { id: 'cookieStore', name: 'cookieStore API获取' },
        { id: 'hybrid', name: '混合模式' }
      ];
      this.init();
    }

    // 初始化
    init() {
      this.createButtons();
      this.loadUserPreferences();
    }

    // 创建右下角按钮
    createButtons() {
      const container = DOMUtils.createElement('div', {
        style: `
          position: fixed;
          right: 20px;
          bottom: 20px;
          z-index: 99999;
          display: flex;
          flex-direction: column;
          gap: 10px;
        `
      });

      // 设置按钮
      const settingsBtn = this.createButton('设置', () => this.showSettings());
      
      // 一键复制按钮
      const copyBtn = this.createButton('一键复制', () => this.copyAll());
      
      // 展示细节按钮
      const detailBtn = this.createButton('展示细节', () => this.showDetails());

      container.appendChild(settingsBtn);
      container.appendChild(copyBtn);
      container.appendChild(detailBtn);
      document.body.appendChild(container);
    }

    // 创建单个按钮
    createButton(text, onClick) {
      const btn = DOMUtils.createElement('button', {
        textContent: text,
        style: `
          padding: 10px 15px;
          background: #4285f4;
          color: white;
          border: none;
          border-radius: 5px;
          cursor: pointer;
          box-shadow: 0 2px 5px rgba(0,0,0,0.2);
          transition: all 0.2s;
        `,
        onclick: onClick
      });

      btn.addEventListener('mouseover', () => {
        btn.style.transform = 'scale(1.05)';
      });

      btn.addEventListener('mouseout', () => {
        btn.style.transform = 'scale(1)';
      });

      return btn;
    }

    // 加载用户偏好设置
    loadUserPreferences() {
      this.selectedMethod = cookieStorage.getValue('cookieMethod', 'gm');
    }

    // 保存用户偏好设置
    saveUserPreferences() {
      cookieStorage.setValue('cookieMethod', this.selectedMethod);
    }

    // 获取Cookie
    async getCookies() {
      try {
        switch (this.selectedMethod) {
          case 'gm':
            return await this.getCookiesByGM();
          case 'document':
            return this.getCookiesByDocument();
          case 'cookieStore':
            return await this.getCookiesByCookieStore();
          case 'hybrid':
            const gmCookies = await this.getCookiesByGM().catch(() => null);
            return gmCookies || this.getCookiesByDocument();
          default:
            return this.getCookiesByGM();
        }
      } catch (e) {
        Qmsg.error('获取Cookie失败: ' + e.message);
        return '';
      }
    }

    // 通过GM API获取Cookie
    async getCookiesByGM() {
      if (!_GM_cookie?.list) return '';
      
      return new Promise((resolve) => {
        _GM_cookie.list({ url: window.location.href }, (cookies) => {
          if (!cookies || !cookies.length) {
            resolve('');
            return;
          }
          
          const cookieStr = cookies.map(c => `${c.name}=${c.value}`).join('; ');
          resolve(cookieStr);
        });
      });
    }

    // 通过document获取Cookie
    getCookiesByDocument() {
      return document.cookie || '';
    }

    // 通过cookieStore API获取Cookie
    async getCookiesByCookieStore() {
      if (!window.cookieStore) {
        Qmsg.error('当前浏览器不支持cookieStore API');
        return '';
      }
      
      try {
        const cookies = await window.cookieStore.getAll();
        if (!cookies || !cookies.length) return '';
        
        return cookies.map(c => `${c.name}=${c.value}`).join('; ');
      } catch (e) {
        Qmsg.error('cookieStore获取失败: ' + e.message);
        return '';
      }
    }

    // 获取User Agent
    getUserAgent() {
      return navigator.userAgent || '';
    }

    // 创建模态框
    createModal(title, content) {
      // 创建模态框容器
      const modal = DOMUtils.createElement('div', {
        style: `
          position: fixed;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background-color: rgba(0,0,0,0.5);
          display: flex;
          justify-content: center;
          align-items: center;
          z-index: 100000;
        `
      });
      
      // 创建模态框内容
      const modalContent = DOMUtils.createElement('div', {
        style: `
          background-color: white;
          border-radius: 8px;
          box-shadow: 0 4px 12px rgba(0,0,0,0.15);
          width: 500px;
          max-width: 90%;
          max-height: 90vh;
          overflow: auto;
        `
      });
      
      // 创建标题栏
      const titleBar = DOMUtils.createElement('div', {
        style: `
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 15px 20px;
          background-color: #f5f5f5;
          border-bottom: 1px solid #e0e0e0;
          border-radius: 8px 8px 0 0;
        `
      });
      
      const titleElement = DOMUtils.createElement('h3', {
        textContent: title,
        style: `
          margin: 0;
          font-size: 18px;
          font-weight: 600;
        `
      });
      
      const closeButton = DOMUtils.createElement('button', {
        textContent: '×',
        style: `
          background: none;
          border: none;
          font-size: 24px;
          cursor: pointer;
          color: #777;
          padding: 0;
          width: 30px;
          height: 30px;
          display: flex;
          align-items: center;
          justify-content: center;
        `,
        onclick: () => modal.remove()
      });
      
      titleBar.appendChild(titleElement);
      titleBar.appendChild(closeButton);
      
      // 创建内容区域
      const contentArea = DOMUtils.createElement('div', {
        style: `
          padding: 20px;
        `
      });
      
      if (typeof content === 'string') {
        contentArea.innerHTML = content;
      } else {
        contentArea.appendChild(content);
      }
      
      // 组装模态框
      modalContent.appendChild(titleBar);
      modalContent.appendChild(contentArea);
      modal.appendChild(modalContent);
      
      // 添加到文档
      document.body.appendChild(modal);
      
      // 返回模态框元素
      return modal;
    }

    // 显示设置面板
    showSettings() {
      try {
        // 创建设置内容
        const content = document.createElement('div');
        
        // 标题
        const title = document.createElement('h3');
        title.textContent = 'Cookie获取方式设置';
        title.style.marginTop = '0';
        title.style.marginBottom = '15px';
        content.appendChild(title);
        
        // 单选按钮组
        const radioGroup = document.createElement('div');
        radioGroup.style.marginBottom = '20px';
        
        this.cookieMethods.forEach(method => {
          const label = document.createElement('label');
          label.style.display = 'block';
          label.style.marginBottom = '10px';
          label.style.cursor = 'pointer';
          
          const radio = document.createElement('input');
          radio.type = 'radio';
          radio.name = 'cookieMethod';
          radio.value = method.id;
          radio.checked = this.selectedMethod === method.id;
          radio.style.marginRight = '8px';
          
          const text = document.createTextNode(method.name);
          
          label.appendChild(radio);
          label.appendChild(text);
          radioGroup.appendChild(label);
        });
        
        content.appendChild(radioGroup);
        
        // 保存按钮
        const saveButton = document.createElement('button');
        saveButton.textContent = '保存设置';
        saveButton.style.padding = '8px 15px';
        saveButton.style.background = '#4285f4';
        saveButton.style.color = 'white';
        saveButton.style.border = 'none';
        saveButton.style.borderRadius = '4px';
        saveButton.style.cursor = 'pointer';
        saveButton.style.fontSize = '14px';
        
        saveButton.onclick = () => {
          // 获取选中的方法
          const selectedRadio = content.querySelector('input[name="cookieMethod"]:checked');
          if (selectedRadio) {
            this.selectedMethod = selectedRadio.value;
            this.saveUserPreferences();
            modal.remove();
            Qmsg.success('设置已保存');
          }
        };
        
        content.appendChild(saveButton);
        
        // 创建模态框
        const modal = this.createModal('Cookie工具设置', content);
      } catch (e) {
        console.error('设置面板创建失败:', e);
        Qmsg.error('设置面板创建失败: ' + e.message);
      }
    }

    // 显示细节面板
    async showDetails() {
      try {
        const cookies = await this.getCookies();
        const ua = this.getUserAgent();
        
        // 创建内容
        const content = document.createElement('div');
        
        // UA部分
        const uaLabel = document.createElement('label');
        uaLabel.textContent = 'User Agent:';
        uaLabel.style.display = 'block';
        uaLabel.style.marginBottom = '5px';
        uaLabel.style.fontWeight = 'bold';
        content.appendChild(uaLabel);
        
        const uaTextarea = document.createElement('textarea');
        uaTextarea.value = ua;
        uaTextarea.readOnly = true;
        uaTextarea.style.width = '100%';
        uaTextarea.style.height = '80px';
        uaTextarea.style.marginBottom = '10px';
        uaTextarea.style.padding = '8px';
        uaTextarea.style.boxSizing = 'border-box';
        uaTextarea.style.border = '1px solid #ddd';
        uaTextarea.style.borderRadius = '4px';
        uaTextarea.style.resize = 'none';
        content.appendChild(uaTextarea);
        
        const uaCopyButton = document.createElement('button');
        uaCopyButton.textContent = '复制UA';
        uaCopyButton.style.padding = '5px 10px';
        uaCopyButton.style.background = '#4285f4';
        uaCopyButton.style.color = 'white';
        uaCopyButton.style.border = 'none';
        uaCopyButton.style.borderRadius = '3px';
        uaCopyButton.style.cursor = 'pointer';
        uaCopyButton.style.marginBottom = '20px';
        uaCopyButton.onclick = () => this.copyToClipboard(ua);
        content.appendChild(uaCopyButton);
        
        // Cookie部分
        const cookieLabel = document.createElement('label');
        cookieLabel.textContent = 'Cookie:';
        cookieLabel.style.display = 'block';
        cookieLabel.style.marginBottom = '5px';
        cookieLabel.style.fontWeight = 'bold';
        content.appendChild(cookieLabel);
        
        const cookieTextarea = document.createElement('textarea');
        cookieTextarea.value = cookies;
        cookieTextarea.readOnly = true;
        cookieTextarea.style.width = '100%';
        cookieTextarea.style.height = '150px';
        cookieTextarea.style.marginBottom = '10px';
        cookieTextarea.style.padding = '8px';
        cookieTextarea.style.boxSizing = 'border-box';
        cookieTextarea.style.border = '1px solid #ddd';
        cookieTextarea.style.borderRadius = '4px';
        cookieTextarea.style.resize = 'none';
        content.appendChild(cookieTextarea);
        
        const cookieCopyButton = document.createElement('button');
        cookieCopyButton.textContent = '复制Cookie';
        cookieCopyButton.style.padding = '5px 10px';
        cookieCopyButton.style.background = '#4285f4';
        cookieCopyButton.style.color = 'white';
        cookieCopyButton.style.border = 'none';
        cookieCopyButton.style.borderRadius = '3px';
        cookieCopyButton.style.cursor = 'pointer';
        cookieCopyButton.onclick = () => this.copyToClipboard(cookies);
        content.appendChild(cookieCopyButton);
        
        // 创建模态框
        this.createModal('详细信息', content);
      } catch (e) {
        console.error('细节面板创建失败:', e);
        Qmsg.error('细节面板创建失败: ' + e.message);
      }
    }

    // 一键复制所有信息
    async copyAll() {
      try {
        const cookies = await this.getCookies();
        const ua = this.getUserAgent();
        const content = `ua="${ua}";cookie="${cookies}";`;
        
        await this.copyToClipboard(content);
        Qmsg.success('复制成功');
      } catch (e) {
        Qmsg.error('复制失败: ' + e.message);
      }
    }

    // 复制到剪贴板
    async copyToClipboard(text) {
      try {
        await navigator.clipboard.writeText(text);
        Qmsg.success('复制成功');
      } catch (err) {
        // 降级处理
        const textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        Qmsg.success('复制成功');
      }
    }
  }

  // 页面加载完成后初始化工具
  DOMUtils.ready(() => {
    new CookieTool();
  });

})(Qmsg, DOMUtils, Utils, CryptoJS);